# -*- coding: utf-8 -*-
import pandas as pd
import ast
from collections import Counter
import matplotlib.pyplot as plt
import seaborn as sns

# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


# ==================== 1. 数据加载与预处理 ====================
def load_data(file_path):
    """加载并解析数据（适配你的实际列名）"""
    df = pd.read_csv(file_path)

    # 重命名列（确保列名统一）
    df = df.rename(columns={
        'Unnamed: 0': 'user_name',
        'interest_cluster': 'cluster'  # 将interest_cluster重命名为cluster以适配后续代码
    })

    # 解析interests和activity列（从字符串转字典）
    df['interests'] = df['interests'].apply(ast.literal_eval)
    df['activity'] = df['activity'].apply(ast.literal_eval)

    # 展开activity字典到单独列
    activity_df = pd.json_normalize(df['activity'])
    df = pd.concat([df.drop(['activity'], axis=1), activity_df], axis=1)

    return df


# ==================== 2. 聚类分析工具函数 ====================
def analyze_clusters(df):
    """分析每个聚类的特征"""
    results = {}

    # 分析每个聚类的关键词
    for cluster in sorted(df['cluster'].unique()):
        cluster_data = df[df['cluster'] == cluster]

        # 合并所有用户的关键词
        all_words = []
        for words_dict in cluster_data['interests']:
            all_words.extend(words_dict.keys())

        # 统计高频词
        word_counts = Counter(all_words)
        top_words = word_counts.most_common(10)

        # 收集统计结果
        results[cluster] = {
            'sample_size': len(cluster_data),
            'top_keywords': top_words,
            'price_dist': cluster_data['price_level'].value_counts().to_dict(),
            'avg_sentiment': cluster_data['sentiment'].mean(),
            'avg_reviews': cluster_data['total_reviews'].mean(),
            'avg_active_years': cluster_data['active_years'].mean(),
            'avg_days_since_last': cluster_data['days_since_last'].mean()
        }

    return results


# ==================== 3. 可视化函数 ====================
def plot_cluster_stats(results):
    """绘制聚类统计图表"""
    # 准备数据
    clusters = sorted(results.keys())

    # 创建2x2的子图布局
    fig, axes = plt.subplots(2, 2, figsize=(15, 10))
    axes = axes.flatten()

    # 指标列表
    metrics = [
        ('avg_sentiment', '平均情感分'),
        ('avg_reviews', '平均评论数'),
        ('avg_active_years', '平均活跃年数'),
        ('avg_days_since_last', '平均最近活跃天数')
    ]

    for i, (metric, title) in enumerate(metrics):
        if i >= len(axes):  # 防止指标数量超过子图数量
            break
        values = [results[c][metric] for c in clusters]
        sns.barplot(x=list(clusters), y=values, ax=axes[i], palette='viridis')
        axes[i].set_title(title)
        axes[i].set_xlabel('聚类分组')
        axes[i].set_ylabel(title)

    plt.tight_layout()
    plt.savefig('cluster_comparison.png', dpi=300)
    plt.show()


# ==================== 4. 主执行流程 ====================
if __name__ == "__main__":
    # 加载数据
    df = load_data('user_profiles.csv')

    # 检查数据
    print("数据前5行预览:")
    print(df.head())
    print("\n列名验证:", df.columns.tolist())

    # 分析聚类特征
    cluster_results = analyze_clusters(df)

    # 打印关键结果
    print("\n" + "=" * 50 + "\n聚类分析结果汇总\n" + "=" * 50)
    for cluster, stats in cluster_results.items():
        print(f"\nCluster {cluster} (样本数: {stats['sample_size']})")
        print("-" * 40)
        print(f"TOP关键词: {[word for word, count in stats['top_keywords']]}")
        print(f"消费水平分布: {stats['price_dist']}")
        print(f"平均情感分: {stats['avg_sentiment']:.2f}")
        print(f"平均评论数: {stats['avg_reviews']:.1f}")
        print(f"平均活跃年数: {stats['avg_active_years']:.1f}")
        print(f"平均最近活跃天数: {stats['avg_days_since_last']:.1f}")

    # 可视化
    plot_cluster_stats(cluster_results)

    # 保存详细结果
    pd.DataFrame.from_dict(cluster_results, orient='index').to_csv('cluster_analysis_details.csv')
    print("\n分析结果已保存到 cluster_analysis_details.csv")

    # 生成关键词词云（按聚类分组）
    for cluster in df['cluster'].unique():
        cluster_words = ' '.join([' '.join(list(d.keys())) for d in df[df['cluster'] == cluster]['interests']])
        if cluster_words.strip():
            wordcloud = WordCloud(
                font_path='simhei.ttf',
                width=800,
                height=400,
                background_color='white'
            ).generate(cluster_words)

            plt.figure(figsize=(10, 5))
            plt.imshow(wordcloud, interpolation='bilinear')
            plt.axis('off')
            plt.title(f'Cluster {cluster} 关键词词云')
            plt.savefig(f'cluster_{cluster}_wordcloud.png', bbox_inches='tight', dpi=300)
            plt.close()
            print(f"Cluster {cluster} 词云已保存")